package org.riotfamily.example;

import org.mortbay.jetty.AbstractConnector;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.security.HashUserRealm;
import org.mortbay.jetty.security.SslSocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;

/**
 * Programmatic start of Jetty Servlet Container.
 *
 * @author JFISCHER
 *
 */
public class JettyLauncher {

	private static void initConnector(AbstractConnector connector) {
		// Set some timeout options to make debugging easier.
		connector.setMaxIdleTime(1000 * 60 * 60);
		connector.setSoLingerTime(-1);
	}

	public static void main(String[] args) throws Exception {
		Server server = new Server();
		SocketConnector httpConnector = new SocketConnector();
		initConnector(httpConnector);
		httpConnector.setPort(8080);
		httpConnector.setConfidentialPort(8443);

		SslSocketConnector httpsConnector = new SslSocketConnector();
		initConnector(httpsConnector);
		httpsConnector.setPort(8443);
		httpsConnector.setKeystore("conf/jetty/localhost.ks");
		httpsConnector.setKeyPassword("password");

		server.setConnectors(new Connector[] { httpConnector, httpsConnector });
        HashUserRealm realm = new HashUserRealm("Item Update Availability", "conf/jetty/realm.properties");
        server.addUserRealm(realm);

		WebAppContext context = new WebAppContext();
		context.setServer(server);
		context.setContextPath("/");
		context.setWar("webapp");

		server.addHandler(context);

		try {
			System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
			server.start();
			System.in.read();
			System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
			// while (System.in.available() == 0) {
			// Thread.sleep(5000);
			// }
			server.stop();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}
	}
}
